package com.binguo.thirdPay.wuZhenPay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binguo.model.model.CashierDesk;
import com.binguo.model.model.CashierDeskWuzhen;
import com.binguo.model.repository.CashierDeskRepository;
import com.binguo.model.repository.CashierDeskWuzhenRepository;
import com.binguo.thirdPay.MD5Util;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yuritian
 * @Title: WuZhenPay
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2019-07-3014:01
 */
@Service
public class WuZhenPayService {

    private static final String SECRET = "d3eda6b25ac8e4b57369fee3e80a574a";

    private static final Integer MODELID = 51;

    @Resource
    private  CashierDeskRepository cashierDeskRepository;

    @Resource
    private CashierDeskWuzhenRepository cashierDeskWuzhenRepository;

    public static void main(String[] args) {
        WuZhenPayService wuZhenPayService = new WuZhenPayService();
        wuZhenPayService.deviceActivation(776);
    }

    public Map<String, Integer> deviceActivation(Integer cashierDeskID){
        Map<String,Integer> deviceResult = new HashMap<>();
        CashierDesk cashierDesk = cashierDeskRepository.findById(cashierDeskID);
        String code = cashierDesk.getCcode();
        SortedMap<String, Object> param = new TreeMap<>();
        Long time = System.currentTimeMillis();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(df.format(new Date(time)));
        param.put("timestamp",time.toString());
        param.put("code",code);
        param.put("modelId",MODELID);
//        JSONObject result = httpWuZhen(param,"http://merchant-api.wuzhenpay.com/open/deviceActivation");
        JSONObject result = httpWuZhen(param,"http://cbpay.wuzhenpay.com/open/deviceActivation");
        if (null != result){
            result = result.getJSONObject("data");
            Integer merchantId = result.getInteger("merchantId");
            Integer deviceId = result.getInteger("deviceId");
            Integer canTurnOver = result.getInteger("canTurnOver");
            Integer canRefund = result.getInteger("canRefund");
            CashierDeskWuzhen cashierDeskWuzhen = new CashierDeskWuzhen();
            cashierDeskWuzhen.setCashierdeskid(cashierDeskID);
            cashierDeskWuzhen.setDeviceid(deviceId);
            cashierDeskWuzhen.setMerchantid(merchantId);
            cashierDeskWuzhen.setCanrefund(canRefund);
            cashierDeskWuzhen.setCanturnover(1);
            cashierDeskWuzhenRepository.save(cashierDeskWuzhen);
            deviceResult.put("merchantId",merchantId);
            deviceResult.put("deviceId",deviceId);
            deviceResult.put("canRefund",canRefund);
            deviceResult.put("canTurnOver",1);
          return deviceResult;
        }
        return null;
    }

    public JSONObject wuzhenPay(String authcode,Long totalFee,Integer merchantId,Integer deviceId){
        SortedMap<String, Object> param = new TreeMap<>();
        Long time = System.currentTimeMillis();
        param.put("timestamp",time.toString());
        param.put("payType",0);
        param.put("authCode",authcode);
        param.put("money",totalFee);
        param.put("merchantId",merchantId);
        param.put("deviceId",deviceId);
        JSONObject result = httpWuZhen(param,"https://cbpay.wuzhenpay.com/trade/pay");
        if (null != result){
            result = result.getJSONObject("data");
            Integer status = result.getInteger("payStatus");
            if (status.intValue() == 0){
                String orderId = result.getString("orderId");
                Integer count = 1;
                while (true){
                    try {
                        if (count <= 5) {
                            Thread.sleep(3 * 1000); //设置暂停的时间 3 秒
                            System.out.println("--订单查询支付状态请求第" + count + "次");
                            count++;
                        }else{
                            Thread.sleep(5 * 1000); //设置暂停的时间 5 秒
                            System.out.println("--订单查询支付状态请求第" + count + "次");
                            count++;
                        }
                        if (count == 15){
                            return null;
                        }
                        JSONObject queryJson = wuzhenPayQuery(orderId,merchantId,deviceId);
                        if (null == queryJson){
                            continue;
                        }else {
                            Integer queryStatus = queryJson.getInteger("payStatus");
                            if (queryStatus == 3 || queryStatus == 4){
                                return null;
                            }else if (queryStatus == 1){
                                return result;
                            }
                        }
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }else if (status.intValue() == 1){
                return result;
            }else {
                return null;
            }
        }
        return null;
    }



    public JSONObject wuzhenPayQuery(String orderId,Integer merchantId,Integer deviceId){
        SortedMap<String, Object> param = new TreeMap<>();
        Long time = System.currentTimeMillis();
        param.put("timestamp",time.toString());
        param.put("orderId",orderId);
        param.put("merchantId",merchantId);
        param.put("deviceId",deviceId);
        JSONObject result = httpWuZhen(param,"https://cbpay.wuzhenpay.com/trade/payQuery");
        if (null != result){
            result = result.getJSONObject("data");
            return result;
        }
        return null;
    }

    public void wuzhenRefund(String orderID,Integer merchantId,Integer deviceId,Long refundMoney){
        SortedMap<String, Object> param = new TreeMap<>();
        Long time = System.currentTimeMillis();
        param.put("timestamp",time.toString());
        param.put("orderId",orderID);
        param.put("merchantId",merchantId);
        param.put("refundMoney",refundMoney);
        param.put("deviceId",deviceId);
        httpWuZhen(param,"https://cbpay.wuzhenpay.com/trade/refund");
    }


    private JSONObject httpWuZhen(SortedMap<String, Object> param,String httpurl){
        String sign = "";
        MultiValueMap map = new LinkedMultiValueMap();
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            sign += entry.getKey() + "=" + entry.getValue() + "&";
            map.add(entry.getKey(),entry.getValue());
        }
        sign += "secret="+SECRET;
        System.out.println(sign);
        map.add("sign", MD5Util.MD5Lower32(sign));
        System.out.println(JSON.toJSONString(param));
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity requestBody = new HttpEntity(map, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(httpurl, requestBody, String.class);
        String result = resp.getBody();
        JSONObject resultJson = JSONObject.parseObject(result);
        System.out.println(result);
        String code = resultJson.getString("code");
        if (code.equals("200")){
            return resultJson;
        }
        return null;
    }
}
